package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xxx.pojo.Department;
import com.xxx.pojo.User;
import com.xxx.pojo.vo.UserVo;
import com.xxx.service.UserService;
import com.xxx.config.Request;
import com.xxx.utli.UploadOss;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * 控制层用于处理用户相关的接口请求
 *
 * UserController.java
 * @Author George
 * @Since 2023-07-02
 */
@Api(tags = "用户控制")
@CrossOrigin(origins = {"*", "null"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 连表查询用户信息
     *
     * @return 返回用户列表和总数
     */
    @ApiOperation(value = "根据条件查询用户列表", notes = "根据分页查询参数查询用户列表")
    @PostMapping("/getUserList")
    public Request UserList(
            @RequestParam("workNumber") String workNumber,
            @RequestParam("pageNum") int pageNum,
            @RequestParam("pageSize") int pageSize) {

        Page<User> mapPage = new Page<>(pageNum, pageSize, true);

//        条件查询获取用户信息
        User byId = userService.getById(workNumber);

        MPJLambdaWrapper<User> lambdaWrapper = new MPJLambdaWrapper<User>()
                .select(Department::getDepartmentName)
                .select(User::getName,User::getDeleted,User::getUserName,
                        User::getPhone,User::getPerms,User::getWorkNumber,
                        User::getGmtCreation,User::getIp)
                .leftJoin(Department.class, Department::getDepartmentId, User::getDepartmentId)
                .ne("perms", byId.getPerms())
                .in("perms", Arrays.asList(1, 2));

       userService.selectJoinListPage(mapPage,User.class, lambdaWrapper);

        // 使用PageInfo对象包装查询结果
        List<User> records = mapPage.getRecords();

        // 获取总记录数
        long total = mapPage.getTotal();

        return records.size() > 0 ? Request.suc(total,records) : Request.error("查询用户失败");
    }


    /**
     * 连表查询用户信息
     *
     * @return 返回用户列表和总数
     */
    @ApiOperation(value = "根据条件查询用户列表", notes = "根据分页查询参数查询用户列表")
    @PostMapping("/getUserQueryByCondition")
    public Request UserQueryByCondition(
            @RequestParam("searchValue") String searchValue,
            @RequestParam("workNumber") String workNumber,
            @RequestParam("pageNum") int pageNum,
            @RequestParam("pageSize") int pageSize) {

        Page<User> mapPage = new Page<>(pageNum, pageSize, true);

        // 去除查询条件中的空格
        String finalSearchValue = StringUtils.isNotBlank(searchValue) ? searchValue.trim() : null;
//        条件查询获取用户信息
        User byId = userService.getById(workNumber);

        MPJLambdaWrapper<User> lambdaWrapper = new MPJLambdaWrapper<User>()
                .select(Department::getDepartmentName)
                .select(User::getName,User::getDeleted,User::getUserName,
                        User::getPhone,User::getPerms,User::getWorkNumber,
                        User::getGmtCreation,User::getIp)
                .leftJoin(Department.class, Department::getDepartmentId, User::getDepartmentId)
                .ne("perms", byId.getPerms())
                .in("perms", Arrays.asList(1, 2));


        if (StringUtils.isNotBlank(finalSearchValue)) {
            lambdaWrapper.and(wrapper -> wrapper
                    .like(User::getPhone, finalSearchValue)
                    .or()
                    .like(User::getName, finalSearchValue)
                    .or()
                    .like(User::getUserName, finalSearchValue)
                    .or()
                    .like(Department::getDepartmentName, finalSearchValue));
        }

        userService.selectJoinListPage(mapPage,User.class, lambdaWrapper);

        // 使用PageInfo对象包装查询结果
        List<User> records = mapPage.getRecords();

        // 获取总记录数
        long total = mapPage.getTotal();

        return records.size() > 0 ? Request.suc(total,records) : Request.error("查询用户失败");
    }

    /**
     * 连查询用户全部信息
     *
     * @return 返回用户列表和总数
     */
    @ApiOperation(value = "根据工号查询用户详情", notes = "根据用户工号查询用户全部信息")
    @PostMapping("/userDetailsByWorkNumber")
    public Request getUserDetailsByWorkNumber(
            @RequestParam("workNumber") String workNumber) {
        List<UserVo> userVoList = userService.selectJoinList(UserVo.class,
                new MPJLambdaWrapper<User>()
                        .selectAll(User.class)
                        .selectAll(Department.class)
                        .leftJoin(Department.class, Department::getDepartmentId, User::getDepartmentId)
                        .eq(User::getWorkNumber, workNumber)
        );
        return userVoList.size() > 0 ? Request.suc(userVoList) : Request.error("根据工号查询用户详情失败");
    }

    /**
     * 根据根据部门编号查询用户
     *
     * @return 返回符合条件的用户列表
     */
    @ApiOperation(value = "根据部门分类查询用户", notes = "根据部门分类查询用户")
    @PostMapping("/usersByDepartment")
    public Request getUsersByDepartment(
            @RequestParam("departmentId") String departmentId,
            @RequestParam("pageNum") int pageNum,
            @RequestParam("pageSize") int pageSize) {


        Page<UserVo> mapPage = new Page<>(pageNum, pageSize, true);

        MPJLambdaWrapper<User> wrapper = new MPJLambdaWrapper<User>()
                .selectAll(Department.class)
                .select(User::getName)
                .leftJoin(Department.class, Department::getDepartmentId, User::getDepartmentId)
                .eq(Department::getDepartmentId, departmentId);

        userService.selectJoinListPage(mapPage, UserVo.class, wrapper);

        List<UserVo> userVoList = mapPage.getRecords();
        long total = mapPage.getTotal();

        return userVoList.size() > 0 ? Request.suc(total,userVoList) : Request.error("根据部门分类查询用户失败");
    }

    /**
     * 修改用户信息
     *
     * @param user 部门id
     * @return 返回操作结果
     */
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    @PutMapping("/updateUser")
    public Request updateUser(@Valid
            @RequestBody User user,
            @RequestParam("newWordNumber") Integer newWordNumber) {

        User update = userService.getById(newWordNumber);
        if (update == null) {
            return Request.error("未找到该员工");
        }
        boolean updated = userService.saveOrUpdate(user);
        return updated ? Request.suc() : Request.error("修改用户信息失败");
    }


    /**
     * 添加用户
     *
     * @param user 用户信息
     * @return 返回操作结果
     */
    @ApiOperation(value = "添加新用户", notes = "添加新用户")
    @PostMapping("/addUser")
    public Request addUser(@ModelAttribute User user) {
        boolean saved = userService.save(user);
        return saved ? Request.suc("添加成功") : Request.error("添加用户失败");
    }

    /**
     * 批量禁用/拉黑用户
     *
     * @return 返回操作结果
     */
    @ApiOperation(value = "批量禁用/拉黑用户", notes = "根据工号批量禁用/拉黑用户")
    @DeleteMapping("/disableUsers")
    public Request disableUsersByIds(
            @RequestParam("workNumber") List<Integer> workNumberList) {
        boolean disabled = userService.removeByIds(workNumberList);
        return disabled ? Request.suc() : Request.error("批量禁用/拉黑用户失败");
    }


    /**
     * 重置用户密码
     *
     * @param newWordNumber   部门id
     * @return 返回操作结果
     */
    @ApiOperation(value = "重置密码", notes = "重置用户密码")
    @PostMapping("/resetUserPassword")
    public Request resetUserPassword(
            @RequestParam("newWordNumber") String newWordNumber) {

        User user = userService.getById(newWordNumber);
        if (user == null) {
            return Request.error("未找到该员工");
        }

        user.setPwd("wx" + newWordNumber);
        boolean updated = userService.updateById(user);
        return updated ? Request.suc() : Request.error("重置失败");
    }


    @ApiOperation(value = "查询头部个人信息", notes = "查询头部个人信息")
    @PostMapping("/info")
    public Request getUserInfo(
            @RequestParam("newWordNumber") String newWordNumber) {

            User user = userService.getById(newWordNumber);
            if (user != null) {
                User userInfo = new User();
                userInfo.setAvatar(user.getAvatar());
                userInfo.setUserName(user.getUserName());

                return Request.suc(userInfo); // 返回成功的响应，HTTP 状态码 200
            } else {
                return Request.error(""); // 返回资源不存在的响应，HTTP 状态码 404
            }
    }

    @PostMapping("/upImg")
    public String upImg(@RequestParam("file") MultipartFile file) throws IOException {
        String Url = UploadOss.uploadImage(file);
        System.out.println(Url);
        return Url;
    }

}


